#include "slCamera.hh"

slCamera::slCamera() :
	_phi(0.0), _theta(0.0), _orientation(), _verticalAxe(0, 0, 1),
	_lateralMovement(), _position(), _target()
{

}

slCamera::slCamera(glm::vec3 position, glm::vec3 target, glm::vec3 verticalAxe) :
	_lateralMovement(), _position(position), _target(target), _verticalAxe(verticalAxe)
{

}


void slCamera::orientate(int xRel, int yRel)
{
	_phi += -yRel * 0.5;
	_theta += -xRel * 0.5;

	if (_phi > 89.0)
		_phi = 89;

	if (_phi < -89.0)
		_phi = -89.0;

	float phiRadian = _phi * M_PI / 180;
	float thetaRadian = _theta * M_PI / 180;

	_orientation.x = cos(phiRadian) * sin(thetaRadian);
	_orientation.y = sin(phiRadian);
	_orientation.z = cos(phiRadian) * cos(thetaRadian);

	if (_verticalAxe.x == 1.0)
	{
 		_orientation.x = sin(phiRadian);
    	_orientation.y = cos(phiRadian) * cos(thetaRadian);
    	_orientation.z = cos(phiRadian) * sin(thetaRadian);		
	}
	else if (_verticalAxe.y == 1.0)
	{
		_orientation.x = cos(phiRadian) * sin(thetaRadian);
    	_orientation.y = sin(phiRadian);
    	_orientation.z = cos(phiRadian) * cos(thetaRadian);
	}
	else
	{
		_orientation.x = cos(phiRadian) * cos(thetaRadian);
    	_orientation.y = cos(phiRadian) * sin(thetaRadian);
    	_orientation.z = sin(phiRadian);
	}

	_lateralMovement = glm::cross(_verticalAxe, _orientation);
	_lateralMovement = glm::normalize(_lateralMovement);

	_target = _position + _orientation;
}

glm::vec3 slCamera::getPosition() const
{
	return _position;
}

glm::vec3 slCamera::getTarget() const
{
	return _target;
}

glm::vec3 slCamera::getOrientation() const
{
	return _orientation;
}

void slCamera::move(slInput &input)
{
	if (input.mouseMoved())
		orientate(input.getXRel(), input.getYRel());

	if(input.getKey(SDL_SCANCODE_W))
    {
        _position = _position + _orientation * 0.5f;
        _target = _position + _orientation;
    }
    // Recul de la caméra
    if(input.getKey(SDL_SCANCODE_S))
    {
        _position = _position - _orientation * 0.5f;
        _target = _position + _orientation;
    }
    // Déplacement vers la gauche
    if(input.getKey(SDL_SCANCODE_A))
    {
        _position = _position + _lateralMovement * 0.5f;
        _target = _position + _orientation;
    }
    // Déplacement vers la droite
    if(input.getKey(SDL_SCANCODE_D))
    {
        _position = _position - _lateralMovement * 0.5f;
        _target = _position + _orientation;
    }	
}

void slCamera::lookAt()
{
	gluLookAt(_position.x, _position.y, _position.z,
			  _target.x, _target.y, _target.z,
			  _verticalAxe.x, _verticalAxe.y, _verticalAxe.z);
}

slCamera::~slCamera()
{
	
}